package com.bhs.sansonglogistics.ui.waybill;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.OrderGoodsDataBean;
import com.bhs.sansonglogistics.bean.WaybillBean;
import com.bhs.sansonglogistics.bean.WaybillDataBean;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.HistoryAdapter;
import com.bhs.sansonglogistics.ui.adapter.OrderGoodsAdapter;
import com.bhs.sansonglogistics.ui.adapter.WaybillAdapter;
import com.bhs.sansonglogistics.ui.order.OrderDetailsActivity;
import com.bhs.sansonglogistics.ui.order.OrderOperation;
import com.bhs.sansonglogistics.ui.order.ScanCodeDeliveryActivity;
import com.bhs.sansonglogistics.ui.order.ShipmentsActivity;
import com.bhs.sansonglogistics.ui.order.SignForActivity;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.AutoLineFeedLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 运单查询
 */
public class WaybillSearchActivity extends BaseActivity implements NetCallBack, View.OnClickListener {

    private EditText mEtSearch;
    private TextView mTvHistorySearch;
    private TextView mTvClear;
    private RecyclerView mRvHistorySearch;
    private RecyclerView mRvWaybill;
    private int page = 1;
    private WaybillAdapter waybillAdapter;
    private OrderGoodsAdapter orderGoodsAdapter;
    private final int CONFIRM_ARRIVAL = 102;
    private final int ORDER_GOODS = 103;
    private final int WAYBILL = 104;
    private ClipData mClipData;   //剪切板Data对象
    private ClipboardManager mClipboardManager;   //剪切板管理工具类
    private String[] historyArray;
    private String historySearch;
    private LinkedList<String> HistoryList = new LinkedList<>();
    private HistoryAdapter historyAdapter;
    private ConstraintLayout mClHistorySearch;
    private OrderOperation orderOperation;
    @Override
    public int initLayout() {
        return R.layout.activity_waybill_search;
    }

    @Override
    public void initView() {

        mEtSearch = findViewById(R.id.et_search);
        mTvHistorySearch = findViewById(R.id.tv_history_search);
        mTvClear = findViewById(R.id.tv_clear);
        mTvClear.setOnClickListener(this);
        mRvHistorySearch = findViewById(R.id.rv_history_search);
        mRvWaybill = findViewById(R.id.rv_waybill);
        findViewById(R.id.iv_scan_code).setOnClickListener(this);
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 1;
                    loadData(mEtSearch.getText().toString());
                    search();
                    return true;
                }
                return false;
            }
        });

        historySearch = SharedPreferencesUtils.getString(this, "HistorySearch", null);
        if (historySearch != null) {
            historyArray = historySearch.split(",");
            if (historyArray.length > 30) {
                StringBuilder stringBuffer = new StringBuilder(historyArray[0]);
                for (int i = 1; i < 30; i++) {
                    stringBuffer.append(",");
                    stringBuffer.append(historyArray[i]);
                }
                SharedPreferencesUtils.saveString(this, "HistorySearch", stringBuffer.toString());
            }
        }

        if (historyArray != null) {
            HistoryList.addAll(Arrays.asList(historyArray));
        }
        historyAdapter = new HistoryAdapter(HistoryList);
        mRvHistorySearch.setAdapter(historyAdapter);
        mRvHistorySearch.setLayoutManager(new AutoLineFeedLayoutManager());
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                loadData(HistoryList.get(position));
            }
        });
        mClHistorySearch = findViewById(R.id.cl_history_search);
        historyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                loadData(HistoryList.get(position));
            }
        });

    }

    private Map<String, String> parameters = new ArrayMap<>();

    private void loadData(String search_key) {
        if (search_key.contains("SS")) {
            mRvWaybill.setAdapter(orderGoodsAdapter);
            parameters.put("search_key", search_key);
            parameters.put("from_page", "waybill_search");
            parameters.put("page", String.valueOf(page));
            networkRequest(netApi.get_order_list(parameters), this, ORDER_GOODS);
        } else {
            mRvWaybill.setAdapter(waybillAdapter);
            networkRequest(netApi.getWaybillLis(page, search_key), this, WAYBILL);
        }

    }


    @SuppressLint("NotifyDataSetChanged")
    private void search() {
        String searchContext = mEtSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(searchContext)) {
            boolean isEqual = false;
            for (String s : HistoryList) {
                if (s.equals(searchContext)) {
                    isEqual = true;
                    break;
                }
            }
            if (isEqual) {
                return;
            }
            if (historySearch == null) {
                historySearch = searchContext;
            } else {
                historySearch = searchContext + "," + historySearch;
            }
            SharedPreferencesUtils.saveString(this, "HistorySearch", historySearch);
            HistoryList.addFirst(searchContext);
            historyAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void initData() {
        waybillAdapter = new WaybillAdapter(2);

        mRvWaybill.setLayoutManager(new LinearLayoutManager(this));

        waybillAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(mActivity, WaybillDetailsActivity.class)
                        .putExtra("waybill_sn", waybillAdapter.getData().get(position).getWaybill_sn()));
            }
        });

        waybillAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                WaybillBean data = waybillAdapter.getData().get(position);
                if (view.getId() == R.id.btn_adjust) {
                    startActivity(new Intent(mActivity, AdjustWaybillActivity.class).putExtra("waybill_sn", data.getWaybill_sn()));
                } else {
                    new XPopup.Builder(mActivity)
                            .asConfirm("提示", "确认到达吗？",
                                    "取消", "确定",
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            networkRequest(netApi.waybilConfirmArrival(data.getWaybill_sn()), WaybillSearchActivity.this, CONFIRM_ARRIVAL);
                                        }
                                    }, null, false)
                            .show();
                }
            }
        });
        waybillAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_empty, null));

        orderGoodsAdapter = new OrderGoodsAdapter(1);
        orderGoodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                OrderGoodsBean data = (OrderGoodsBean) adapter.getData().get(position);
                startActivity(new Intent(mActivity, OrderDetailsActivity.class)
                        .putExtra("deliver_sn", data.getDeliver_sn()));
            }
        });
        orderOperation=new OrderOperation(mActivity);
        orderOperation.operation(orderGoodsAdapter);
        orderOperation.setMyClickListener(new MyClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                loadData(mEtSearch.getText().toString());
            }
        });
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == WAYBILL) {
            WaybillDataBean dataBean = new Gson().fromJson(json, WaybillDataBean.class);
            if (dataBean.isStatus()) {
                waybillAdapter.setNewData(dataBean.getData().getList());
                if (!MyUtils.isEmpty(dataBean.getData().getList())) {
                    mClHistorySearch.setVisibility(View.GONE);
                } else {
                    ToastUtil.show("未搜索到记录");
                    mClHistorySearch.setVisibility(View.VISIBLE);
                }
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        } else if (requestCode == ORDER_GOODS) {
            OrderGoodsDataBean dataBean = new Gson().fromJson(json, OrderGoodsDataBean.class);
            if (dataBean.isStatus()) {
                orderGoodsAdapter.setNewData(dataBean.getData().getList());
                if (!MyUtils.isEmpty(dataBean.getData().getList())) {
                    mClHistorySearch.setVisibility(View.GONE);
                } else {
                    ToastUtil.show("未搜索到记录");
                    mClHistorySearch.setVisibility(View.VISIBLE);
                }
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        } else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                page = 1;
                loadData("");
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }


    // Register the launcher and result handler
    private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(),
            result -> {
                if (result.getContents() == null) {
                    //Toast.makeText(WaybillSearchActivity.this, "Cancelled", Toast.LENGTH_LONG).show();
                } else {
                    LogUtils.d(result.getContents());
                }
            });

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.iv_scan_code) {
            ScanOptions options = new ScanOptions();
            options.setDesiredBarcodeFormats(ScanOptions.QR_CODE);
            options.setOrientationLocked(false);
            options.setPrompt("请将二维码置于取景框内扫描");
            barcodeLauncher.launch(options);
        } else if (view.getId() == R.id.tv_clear) {
            SharedPreferencesUtils.clear(this, "HistorySearch");
            HistoryList.clear();
            historyAdapter.notifyDataSetChanged();
        }
    }
}